package com.mes.cloud.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mes.cloud.api.dto.request.*;
import com.mes.cloud.api.dto.response.DictionaryAndModuleDto;
import com.mes.cloud.api.dto.response.SysDictDto;
import com.mes.cloud.api.dto.response.SysDictionaryDto;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.HttpReturnEnums;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.SysDictionaryDao;
import com.mes.cloud.dao.SysModuleTreeDao;
import com.mes.cloud.entity.SysDictionary;
import com.mes.cloud.entity.SysModuleTree;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 字典表
 *
 * @author zhengyangping
 * @version 2019-07-30 13:43:19
 * @email 407892370@qq.com
 */
@Service
public class SysDictionaryService {

    private SysDictionaryDao sysDictionaryDao;

    private IPKeyGenerator iPKeyGenerator;

    private SysModuleTreeDao sysModuleTreeDao;

    @Autowired
    public SysDictionaryService(SysDictionaryDao sysDictionaryDao, IPKeyGenerator iPKeyGenerator, SysModuleTreeDao sysModuleTreeDao) {
        this.sysDictionaryDao = sysDictionaryDao;
        this.iPKeyGenerator = iPKeyGenerator;
        this.sysModuleTreeDao = sysModuleTreeDao;
    }

    /**
     * 描述 字典分页
     *
     * @param pageRequest
     * @return com.shinho.tntframe.core.common.model.CommPager<com.shinho.crm.dict.api.dto.response.SysDictionaryDto>
     * @author 郑样平
     * @date 2019/8/8 17:37
     */
    public CommPager<SysDictionaryDto> selectPage(SysDictionaryPageRequest pageRequest) {
        Page<SysDictionaryDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        //查询条件
        List<SysDictionary> sysDictionaryList = sysDictionaryDao.sysDictionaryList(pageRequest);
        List<SysDictionaryDto> sysDictionaryDtoList = new ArrayList<>();
        for (SysDictionary sysDictionary : sysDictionaryList) {
            SysDictionaryDto sysDictionaryDto = new SysDictionaryDto();
            BeanUtils.copyProperties(sysDictionary, sysDictionaryDto);
            sysDictionaryDtoList.add(sysDictionaryDto);
        }
        //保存上级name
        for (SysDictionaryDto dictDto : sysDictionaryDtoList) {
            SysDictionary dict = new SysDictionary();
            dict.setId(dictDto.getParentId());
            SysDictionary dictionary = sysDictionaryDao.selectByPrimaryKey(dict);
            if (dictionary != null) {
                dictDto.setParentName(dictionary.getName());
            }
        }
        CommPager<SysDictionaryDto> pageResult = new CommPager<>(page, sysDictionaryDtoList);
        return pageResult;
    }

    /**
     * 描述 获取列表
     *
     * @param sysDictionaryRequest
     * @return java.util.List<com.shinho.crm.dict.api.dto.response.SysDictionaryDto>
     * @author 郑样平
     * @date 2019/8/8 17:37
     */
    public List<SysDictionaryDto> list(SysDictionaryRequest sysDictionaryRequest) {
        //查询条件
        List<SysDictionary> sysDictionaryList = sysDictionaryDao.selectList(sysDictionaryRequest);
        List<SysDictionaryDto> sysDictionaryDtoList = new ArrayList<>();
        for (SysDictionary sysDictionary : sysDictionaryList) {
            SysDictionaryDto sysDictionaryDto = new SysDictionaryDto();
            BeanUtils.copyProperties(sysDictionary, sysDictionaryDto);
            sysDictionaryDtoList.add(sysDictionaryDto);
        }
        return sysDictionaryDtoList;
    }

    /**
     * 描述 字典新增
     *
     * @param {sysDictionaryRequest}
     * @return com.shinho.tntframe.core.common.model.JsonResult
     * @author 郑样平
     * @date 2019/8/8 17:36
     */
    public JsonResult insertSelective(SysDictionaryAddRequest sysDictionaryAddRequest) {
        JsonResult jsonResult = new JsonResult();
        SysDictionaryUniqueRequest uniqueRequest = new SysDictionaryUniqueRequest();
        uniqueRequest.setCode(sysDictionaryAddRequest.getCode());
        //uniqueRequest.setName(sysDictionaryAddRequest.getName());
        uniqueRequest.setValue(sysDictionaryAddRequest.getValue());
        int count = sysDictionaryDao.selectUnique(uniqueRequest);
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.UNIQUE.getMessage());
            jsonResult.setCode(HttpStatusEnum.UNIQUE.getCode());
            return jsonResult;
        }
        SysDictionary sysDictionary = new SysDictionary();
        BeanUtils.copyProperties(sysDictionaryAddRequest, sysDictionary);
        sysDictionary.setId(iPKeyGenerator.getGenerateKey());
        sysDictionary.setUpdateDateStr(DateUtil.updateDateStr());
        sysDictionary.setCreateBy(UserUtil.getCreateByName());
        sysDictionary.setUpdateBy(UserUtil.getUpdateByName());
        sysDictionary.setCreateByNo(UserUtil.getCreateByNo());
        sysDictionary.setUpdateByNo(UserUtil.getUpdateByNo());
        int dictionaryCount = sysDictionaryDao.insertSelective(sysDictionary);
        if (dictionaryCount == 1) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
        } else {
            jsonResult.setMsg(HttpStatusEnum.FAIL.getMessage());
            jsonResult.setCode(HttpStatusEnum.FAIL.getCode());
        }
        return jsonResult;
    }

    /**
     * 描述 字典修改
     *
     * @param {sysDictionaryRequest}
     * @return com.shinho.tntframe.core.common.model.JsonResult
     * @author 郑样平
     * @date 2019/8/8 17:35
     */
    public JsonResult updateSelectiveById(SysDictionaryUpdateRequest sysDictionaryUpdateRequest) {
        JsonResult jsonResult = new JsonResult();
        SysDictionaryUniqueRequest uniqueRequest = new SysDictionaryUniqueRequest();
        uniqueRequest.setCode(sysDictionaryUpdateRequest.getCode());
        //uniqueRequest.setName(sysDictionaryUpdateRequest.getName());
        uniqueRequest.setValue(sysDictionaryUpdateRequest.getValue());
        SysDictionary sysDictionary1 = sysDictionaryDao.selectByPrimaryKey(sysDictionaryUpdateRequest.getId());
        int count1 = sysDictionaryDao.selectUnique(uniqueRequest);
        //校验不等于本身，且存在记录
        if (!StringUtils.isEmpty(sysDictionaryUpdateRequest.getCode())
                && !sysDictionary1.getName().equals(sysDictionaryUpdateRequest.getName())
                && !sysDictionary1.getValue().equals(sysDictionaryUpdateRequest.getValue())
                && count1 > 0) {
            jsonResult.setMsg(HttpStatusEnum.UNIQUE.getMessage());
            jsonResult.setCode(HttpStatusEnum.UNIQUE.getCode());
            return jsonResult;
        }
        SysDictionary sysDictionary = new SysDictionary();
        BeanUtils.copyProperties(sysDictionaryUpdateRequest, sysDictionary);
        sysDictionary.setUpdateDateStr(DateUtil.updateDateStr());
        sysDictionary.setUpdateBy(UserUtil.getUpdateByName());
        sysDictionary.setUpdateByNo(UserUtil.getUpdateByNo());
        int count2 = sysDictionaryDao.updateByPrimaryKeySelective(sysDictionary);
        if (count2 == 1) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
        } else {
            jsonResult.setMsg(HttpStatusEnum.FAIL.getMessage());
            jsonResult.setCode(HttpStatusEnum.FAIL.getCode());
        }
        return jsonResult;
    }

    /**
     * 描述 获取字典对象
     *
     * @param id
     * @return com.shinho.tntframe.core.common.model.JsonResult<com.shinho.crm.dict.api.dto.response.SysDictionaryDto>
     * @author 郑样平
     * @date 2019/8/8 17:34
     */
    public JsonResult<SysDictionaryDto> get(String id) {
        JsonResult jsonResult = new JsonResult();
        SysDictionary sysDictionary = sysDictionaryDao.selectByPrimaryKey(id);
        if (sysDictionary == null) {
            jsonResult.setMsg(HttpStatusEnum.FAIL.getMessage());
            jsonResult.setCode(HttpStatusEnum.FAIL.getCode());
            return jsonResult;
        }
        SysDictionaryDto sysDictionaryDto = new SysDictionaryDto();
        BeanUtils.copyProperties(sysDictionary, sysDictionaryDto);
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
        jsonResult.setCode(HttpStatusEnum.OK.getCode());
        jsonResult.setData(sysDictionaryDto);
        return jsonResult;
    }

    /**
     * 描述 查询字典树
     *
     * @param
     * @return java.util.List<com.shinho.crm.dict.api.dto.response.DictionaryAndModuleDto>
     * @author 郑样平
     * @date 2019/8/8 17:24
     */
    public List<DictionaryAndModuleDto> treeList(TreeLIstRequest treeLIstRequest) {
        List<DictionaryAndModuleDto> dictionaryAndModuleDtoList = new ArrayList<DictionaryAndModuleDto>();
        SysModuleTree sysModuleTree = new SysModuleTree();
        sysModuleTree.setType(Constants.MODULE_TREE_TEPE);
        sysModuleTree.setDelFlag(Constants.DEL_FLAG_NO);
        // 字典树里数据
        List<SysModuleTree> sysModuleTreeList = sysModuleTreeDao.select(sysModuleTree);
        Collections.sort(sysModuleTreeList, Comparator.comparing(SysModuleTree::getCreateTime));
        for (SysModuleTree sysModuleTree1 : sysModuleTreeList) {
            DictionaryAndModuleDto dictionaryAndModuleDto1 = new DictionaryAndModuleDto();
            BeanUtils.copyProperties(sysModuleTree1, dictionaryAndModuleDto1);
            dictionaryAndModuleDtoList.add(dictionaryAndModuleDto1);
        }
        SysDictionary sysDictionary = new SysDictionary();
        sysDictionary.setDelFlag(Constants.DEL_FLAG_NO);
        sysDictionary.setEnableFlag(Constants.ENABLE_FLAG_YES);
        //字典里面数据
        List<SysDictionary> sysDictionaryList = sysDictionaryDao.select(sysDictionary);
        if (!StringUtils.isEmpty(treeLIstRequest.getParentId()) && !Constants.PAREN_TTREE.equals(treeLIstRequest.getParentId())) {
            SysDictionary sysDictionary1 = sysDictionaryDao.selectByPrimaryKey(treeLIstRequest.getParentId());
            if(Constants.ENABLE_FLAG_NO.equals(sysDictionary1.getEnableFlag())){
                sysDictionaryList.add(sysDictionary1);
            }
        }
        for (SysDictionary sysDictionary1 : sysDictionaryList) {
            sysDictionary1.setParentId(sysDictionary1.getModuleTreeId());
            DictionaryAndModuleDto dictionaryAndModuleDto1 = new DictionaryAndModuleDto();
            BeanUtils.copyProperties(sysDictionary1, dictionaryAndModuleDto1);
            dictionaryAndModuleDtoList.add(dictionaryAndModuleDto1);
        }
        return dictionaryAndModuleDtoList;
    }

    /**
     * 描述 是否默认
     *
     * @param {id, moduleTreeId}
     * @return com.shinho.tntframe.core.common.model.JsonResult
     * @author 郑样平
     * @date 2019/8/8 17:23
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateDefaultFlag(SysDictionaryDefaultFlagRequest sysDictionaryDefaultFlagRequest) {
        SysDictionary sysDictionary = new SysDictionary();
        sysDictionary.setModuleTreeId(sysDictionaryDefaultFlagRequest.getModuleTreeId());
        sysDictionary.setId(sysDictionaryDefaultFlagRequest.getId());
        sysDictionary.setDefaultFlag(Integer.parseInt(sysDictionaryDefaultFlagRequest.getDefaultFlag()));
        sysDictionary.setUpdateDateStr(DateUtil.updateDateStr());
        sysDictionary.setUpdateBy(UserUtil.getUpdateByName());
        sysDictionary.setUpdateByNo(UserUtil.getUpdateByNo());
        //根据ID 设置默认为1
        sysDictionaryDao.updateByPrimaryKeySelective(sysDictionary);
        //全部修改为0
        int count = sysDictionaryDao.updateDefaultFlag(sysDictionary);
        JsonResult jsonResult = new JsonResult();
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
        } else {
            jsonResult.setMsg(HttpStatusEnum.FAIL.getMessage());
            jsonResult.setCode(HttpStatusEnum.FAIL.getCode());
        }
        return jsonResult;
    }

    /**
     * 描述  批量启用-禁用
     *
     * @param dictRequest
     * @return com.shinho.tntframe.core.common.model.JsonResult
     * @author 郑样平
     * @date 2019/8/8 17:22
     */
    public JsonResult batchEnable(SysDicibatchEnableRequest dictRequest) {
        dictRequest.setUpdateDateStr(DateUtil.updateDateStr());
        dictRequest.setUpdateBy(UserUtil.getUpdateByName());
        dictRequest.setUpdateByNo(UserUtil.getUpdateByNo());
        int count = sysDictionaryDao.batchEnable(dictRequest);
        JsonResult jsonResult = new JsonResult();
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
        } else {
            jsonResult.setMsg(HttpStatusEnum.FAIL.getMessage());
            jsonResult.setCode(HttpStatusEnum.FAIL.getCode());
        }
        return jsonResult;
    }

    /**
     * 描述  根据编码和值下级列表
     *
     * @param codeAndValueRequest
     * @return java.util.List<com.shinho.crm.dict.api.dto.response.SysDictionaryDto>
     * @author 郑样平
     * @date 2019/9/10 10:30
     */
    public JsonResult<List<SysDictionaryDto>> codeAndValueList(CodeAndValueRequest codeAndValueRequest) {
        //查询条件

        List<SysDictionaryDto> sysDictionaryDtoList = new ArrayList<>();
        JsonResult<List<SysDictionaryDto>> jsonResult = new JsonResult<>();
        SysDictionary sysDictionary = sysDictionaryDao.codeAndValueList(codeAndValueRequest);
        //为空直接返回
        if (sysDictionary == null) {
            return jsonResult.setCode(HttpReturnEnums.Success.value()).setData(sysDictionaryDtoList);
        }
        List<SysDictionary> select = new ArrayList<SysDictionary>();
        SysDictionary sysDictionary1 = new SysDictionary();
        sysDictionary1.setParentId(sysDictionary.getId());
        sysDictionary1.setEnableFlag(Constants.ENABLE_FLAG_YES);
        sysDictionary1.setCode(codeAndValueRequest.getCode());
        select = sysDictionaryDao.select(sysDictionary1);
        for (SysDictionary sysDictionarys : select) {
            SysDictionaryDto sysDictionaryDto = new SysDictionaryDto();
            BeanUtils.copyProperties(sysDictionarys, sysDictionaryDto);
            sysDictionaryDtoList.add(sysDictionaryDto);
        }
        return jsonResult.setCode(HttpReturnEnums.Success.value()).setData(sysDictionaryDtoList);
    }

    /**
     * 描述 根据code 显示值去模糊匹配显示值
     *
     * @param codeAndNameListRequest
     * @return com.shinho.tntframe.core.common.model.JsonResult<java.util.List < com.shinho.crm.dict.api.dto.response.SysDictionaryDto>>
     * @author 郑样平
     * @date 2019/9/27 14:38
     */
    public List<SysDictionaryDto> codeAndNameList(CodeAndNameListRequest codeAndNameListRequest) {
        //查询条件
        List<SysDictionary> sysDictionaryList = sysDictionaryDao.codeAndNameList(codeAndNameListRequest);
        List<SysDictionaryDto> sysDictionaryDtoList = new ArrayList<>();
        for (SysDictionary sysDictionary : sysDictionaryList) {
            SysDictionaryDto sysDictionaryDto = new SysDictionaryDto();
            BeanUtils.copyProperties(sysDictionary, sysDictionaryDto);
            sysDictionaryDtoList.add(sysDictionaryDto);
        }
        return sysDictionaryDtoList;
    }

    /**
     * @Author ysd
     * @Description 根据编码list
     * @Date 22:37 2019/12/17
     **/
    public JsonResult<List<SysDictionaryDto>> findListByCodes(List<String> codes) {
        JsonResult<List<SysDictionaryDto>> jsonResult = new JsonResult<>();
        //查询条件
        List<SysDictionary> sysDictionaryList = sysDictionaryDao.findListByCodes(codes);
        List<SysDictionaryDto> sysDictionaryDtoList = new ArrayList<>();
        for (SysDictionary sysDictionary : sysDictionaryList) {
            SysDictionaryDto sysDictionaryDto = new SysDictionaryDto();
            BeanUtils.copyProperties(sysDictionary, sysDictionaryDto);
            sysDictionaryDtoList.add(sysDictionaryDto);
        }
        return jsonResult.setCode(HttpReturnEnums.Success.value()).setMsg(HttpStatusEnum.OK.getMessage()).setData(sysDictionaryDtoList);
    }

    public List<SysDictDto> getListByCode(String code) {
        //查询条件
        List<String> codeList = new ArrayList<>();
        codeList.add(code);
        List<SysDictionary> sysDictionaryList = sysDictionaryDao.findListByCodes(codeList);
        List<SysDictDto> sysDictDtoList = new ArrayList<>();
        for (SysDictionary sysDictionary : sysDictionaryList) {
            SysDictDto sysDictDto = new SysDictDto();
            BeanUtils.copyProperties(sysDictionary, sysDictDto);
            sysDictDtoList.add(sysDictDto);
        }
        return sysDictDtoList;
    }
}
